############################################################################################################
#
#  Date          Author          Changes
#  2024/09/14    veenus.yu       Created
#
###########################################################################################################
import serial_module
import serial
import time
import os
import sys
import re
import datetime
import fnmatch
import subprocess
import random
import threading



class Stress_script(object):
    """docstring for fourRouteAPN"""

    def __init__(self, **ports):

        self.serial_obj = serial_module.serialObj(**ports)
        self.at_log = "AT_LOG_{}.log".format(
            time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
        )
        self.debug_log = "DEBUG_LOG_{}.log".format(
            time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
        )
        self.aux_at_log = "AUX_AT_LOG_{}.log".format(
            time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
        )
        self.aux_debug_log = "AUX_DEBUG_LOG_{}.log".format(
            time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
        )
        self.result_log = "RESULT_LOG_{}.log".format(
            time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
        )

    def writeRuntimesToLog_at(self, runTimes):
        with open(self.at_log, "a") as file_object:
            file_object.write(
                "\r\n{}    runTime:{} {} {}\r\n".format(
                    "<<" * 5,
                    str(runTimes),
                    time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()),
                    ">>" * 5,
                )
            )

    def writeRuntimesToLog_debug(self, runTimes):
        with open(self.debug_log, "a") as file_object:
            file_object.write(
                "\r\n{}    runTime:{} {} {}\r\n".format(
                    "<<" * 5,
                    str(runTimes),
                    time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()),
                    ">>" * 5,
                )
            )

    def writeRuntimesToLog_aux_debug(self, runTimes):
        with open(self.aux_debug_log, "a") as file_object:
            file_object.write(
                "\r\n{}    runTime:{} {} {}\r\n".format(
                    "<<" * 5,
                    str(runTimes),
                    time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()),
                    ">>" * 5,
                )
            )

    def writeRuntimesToLog_aux_at(self, runTimes):
        with open(self.aux_at_log, "a") as file_object:
            file_object.write(
                "\r\n{}    runTime:{} {} {}\r\n".format(
                    "<<" * 5,
                    str(runTimes),
                    time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()),
                    ">>" * 5,
                )
            )

    def writeRuntimesToLog_result(self, runTimes):
        with open(self.result_log, "a") as file_object:
            file_object.write(
                "\r\n{}    runTime:{} {} {}\r\n".format(
                    "<<" * 5,
                    str(runTimes),
                    time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()),
                    ">>" * 5,
                )
            )

    def IntoAdbShell(adbID):
        process = subprocess.Popen(
            "adb -s {} shell ".format(adbID),
            shell=True,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            encoding="utf-8",
        )
        return process

    # 检查A模块是否登录
    def login_Device(self):
        curr_time = datetime.datetime.now()
        print(
            "[{}] A模组开始登录...\n".format(
                time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
            )
        )
        while True:
            time.sleep(1)
            self.serial_obj.serial_write(self.serial_obj.debug_serial, "\r\n")
            result = self.serial_obj.serial_read(
                self.serial_obj.debug_serial, self.debug_log
            )
            if "#" in result:
                print(
                    "[{}] A模组已经是登录状态\n".format(
                        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                    )
                )
                self.serial_obj.serial_write(self.serial_obj.debug_serial, "\003\r\n")
                self.serial_obj.serial_read(
                    self.serial_obj.debug_serial, self.debug_log
                )
                break

            if "login:" in result:
                self.serial_obj.serial_write(self.serial_obj.debug_serial, "root\r\n")
                time.sleep(1)
                self.serial_obj.serial_read(
                    self.serial_obj.debug_serial, self.debug_log
                )
                self.serial_obj.serial_write(
                    self.serial_obj.debug_serial, "oelinux123\r\n"
                )
                time.sleep(1)
                self.serial_obj.serial_read(
                    self.serial_obj.debug_serial, self.debug_log
                )

            if "~ #" in result:
                print(
                    "[{}] A模块登录成功\n".format(
                        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                    )
                )
                break
            else:
                self.serial_obj.serial_write(self.serial_obj.debug_serial, "\003\r\n")

            tmp_time = datetime.datetime.now()
            if (tmp_time - curr_time).seconds > 200:
                print(
                    "[{}] A模块登录失败\n".format(
                        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                    )
                )
                sys.exit()

    # 检查B模块是否登录
    def aux_login_Device(self):
        curr_time = datetime.datetime.now()
        print(
            "[{}] B模组开始登录...\n".format(
                time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
            )
        )
        while True:
            time.sleep(1)
            self.serial_obj.serial_write(self.serial_obj.aux_debug_port, "\r\n")
            result = self.serial_obj.serial_read(
                self.serial_obj.aux_debug_port, self.aux_debug_log
            )
            if "#" in result:
                print(
                    "[{}] B模组已经是登录状态\n".format(
                        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                    )
                )
                self.serial_obj.serial_write(self.serial_obj.aux_debug_port, "\003\r\n")
                self.serial_obj.serial_read(
                    self.serial_obj.aux_debug_port, self.aux_debug_log
                )
                break

            if "login:" in result:
                self.serial_obj.serial_write(self.serial_obj.aux_debug_port, "root\r\n")
                time.sleep(1)
                self.serial_obj.serial_read(
                    self.serial_obj.aux_debug_port, self.aux_debug_log
                )
                self.serial_obj.serial_write(
                    self.serial_obj.aux_debug_port, "oelinux123\r\n"
                )
                time.sleep(1)
                self.serial_obj.serial_read(
                    self.serial_obj.aux_debug_port, self.aux_debug_log
                )

            if "~ #" in result:
                print(
                    "[{}] B模组登录成功\n".format(
                        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                    )
                )
                break
            else:
                self.serial_obj.serial_write(self.serial_obj.aux_debug_port, "\003\r\n")

            tmp_time = datetime.datetime.now()
            if (tmp_time - curr_time).seconds > 200:
                print(
                    "[{}] B模块登录失败\n".format(
                        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                    )
                )
                sys.exit()

    def checkNetWork_A(self):
        i = 0
        while i < 30:
            self.serial_obj.serial_write(
                self.serial_obj.at_serial,
                "AT+CREG?;+CGREG?;+CEREG?;+C5GREG?;+QCSQ;+QNWINFO;+COPS?;\r\n",
            )
            time.sleep(2)
            response_reg = self.serial_obj.serial_read(
                self.serial_obj.at_serial, self.at_log
            )
            # if ("+CEREG: 0,1" in response_reg and "NR5G-SA"  in response_reg) or ("+CEREG: 0,1" in response_reg and "LTE"  in response_reg):
            if "NR5G-SA" in response_reg:
                print(
                    "[{}] A模块注网正常.\n".format(
                        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                    )
                )
                break
            i += 1
        if i == 30:
            print(
                "[{}] A模块注网不正常，failed.\n".format(
                    time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                )
            )
            sys.exit()

    def checkNetWork_B(self):
        i = 0
        while i < 30:
            self.serial_obj.serial_write(
                self.serial_obj.aux_at_serial,
                "AT+CREG?;+CGREG?;+CEREG?;+C5GREG?;+QCSQ;+QNWINFO;+COPS?;\r\n",
            )
            time.sleep(2)
            response_reg = self.serial_obj.serial_read(
                self.serial_obj.aux_at_serial, self.aux_at_log
            )
            if ("+CEREG: 0,1" in response_reg and "NR5G-SA" in response_reg) or (
                "+CEREG: 0,1" in response_reg and "LTE" in response_reg
            ):
                print(
                    "[{}] B模块注网正常.\n".format(
                        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                    )
                )
                break
            i += 1
        if i == 30:
            print(
                "[{}] B模块注网不正常，failed.\n".format(
                    time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
                )
            )
            sys.exit()

    def get_api_num(self, raw_data, query_name):
        # 数据清洗并存储到字典
        api_dict = {}
        for line in raw_data.strip().split("\n"):
            parts = line.split(maxsplit=1)
            if len(parts) != 2:  # 检查格式是否有效
                continue
            try:
                key = int(parts[0])  # 转换编号为整数
                value = parts[1].strip()  # 去除功能名称多余空格
                if value:  # 确保名称不为空
                    api_dict[key] = value
            except ValueError:
                continue  # 跳过无法转换为整数的行

        # 创建反向字典
        name_to_key = {value: key for key, value in api_dict.items()}
        print(name_to_key)
        # 根据名称查询编号
        return name_to_key.get(query_name, None)

    # A模块拨号
    def dial_net_A(self):
        self.serial_obj.serial_write(
            self.serial_obj.debug_serial, "ql_netcall -d &\r\n"
        )
        result = self.serial_obj.serial_read(
            self.serial_obj.debug_serial, self.debug_log
        )

    # 进入A模块测试接口
    def test_api_A(self):

        # self.serial_obj.serial_write(self.serial_obj.debug_port, "cd /data && ./test_sdk_api\r\n")
        self.serial_obj.serial_write(
            self.serial_obj.debug_serial, "cd /data && ./test_sdk_ms_api\r\n"
        )
        time.sleep(1)
        result = self.serial_obj.serial_read(
            self.serial_obj.debug_serial, self.debug_log
        )
        print(result)
        wifi_num = self.get_api_num(result, "wifi")
        print(wifi_num)
        self.serial_obj.serial_write(self.serial_obj.debug_serial, f"{wifi_num}\r\n")
        time.sleep(1)
        result = self.serial_obj.serial_read(
            self.serial_obj.debug_serial, self.debug_log
        )
        print(result)
        time.sleep(1)
        wifi_init_num = self.get_api_num(result, "ql_wifi_init")
        print(wifi_init_num)
        self.serial_obj.serial_write(
            self.serial_obj.debug_serial, f"{wifi_init_num}\r\n"
        )
        time.sleep(1)
        result_wifi = self.serial_obj.serial_read(
            self.serial_obj.debug_serial, self.debug_log
        )
        print(result_wifi)
        wifi_enable_num = self.get_api_num(result, "ql_wifi_enable")
        print(wifi_enable_num)
        self.serial_obj.serial_write(
            self.serial_obj.debug_serial, f"{wifi_enable_num}\r\n"
        )
        time.sleep(3)
        ql_wifi_ap_start_num = self.get_api_num(result, "ql_wifi_ap_start")
        self.serial_obj.serial_write(
            self.serial_obj.debug_serial, f"{ql_wifi_ap_start_num}\r\n0\r\n"
        )
        wifi_ap_satart_result = self.serial_obj.serial_read(
            self.serial_obj.debug_serial, self.debug_log
        )
        print(wifi_ap_satart_result)

    # 进入B模块测试接口
    def test_api_B(self):
        # self.serial_obj.serial_write(self.serial_obj.aux_debug_port, "cd /data && ./test_sdk_api\r\n")
        self.serial_obj.serial_write(
            self.serial_obj.aux_debug_port, "cd /data && ./test_sdk_ms_api\r\n"
        )
        time.sleep(1)
        result = self.serial_obj.serial_read(
            self.serial_obj.aux_debug_port, self.aux_debug_log
        )
        print(result)
        wifi_num = self.get_api_num(result, "wifi")
        print(wifi_num)
        self.serial_obj.serial_write(self.serial_obj.aux_debug_port, f"{wifi_num}\r\n")
        time.sleep(1)
        result_wifi = self.serial_obj.serial_read(
            self.serial_obj.aux_debug_port, self.aux_debug_log
        )
        print(result_wifi)
        wifi_init_num = self.get_api_num(result_wifi, "ql_wifi_init")
        self.serial_obj.serial_write(
            self.serial_obj.aux_debug_port, f"{wifi_init_num}\r\n"
        )
        time.sleep(1)
        result_wifi_init = self.serial_obj.serial_read(
            self.serial_obj.aux_debug_port, self.aux_debug_log
        )
        print(result_wifi_init)
        wifi_enable_num = self.get_api_num(result_wifi, "ql_wifi_enable")
        print(wifi_enable_num)
        self.serial_obj.serial_write(
            self.serial_obj.aux_debug_port, f"{wifi_enable_num}\r\n"
        )
        time.sleep(3)
        result_wifi_enable = self.serial_obj.serial_read(
            self.serial_obj.aux_debug_port, self.aux_debug_log
        )
        print(result_wifi_enable)
        wifi_work_mode_set_num = self.get_api_num(result_wifi, "ql_wifi_work_mode_set")
        print(wifi_work_mode_set_num)
        self.serial_obj.serial_write(
            self.serial_obj.aux_debug_port, f"{wifi_work_mode_set_num}\n"
        )
        time.sleep(0.5)
        self.serial_obj.serial_write(self.serial_obj.aux_debug_port, "0\n")
        time.sleep(1)
        result_wifi_work_mode_set = self.serial_obj.serial_read(
            self.serial_obj.aux_debug_port, self.aux_debug_log
        )
        print(result_wifi_work_mode_set)


# ============================================================================================#
# 端口定义
# A模块端口
AT_PORT = "COM66"
DEBUG_PORT = "COM4"

# B模块端口
AUX_AT_PORT = "COM66"
AUX_DEBUG_PORT = "COM4"

# # A模块号码
# phoneNumA = "13053133078"

# # B模块号码
# phoneNumB = "18256942153"

# 记录运行次数
runTimes = 0
module = Stress_script(
    debug_port=DEBUG_PORT,
    at_port=AT_PORT,
    # aux_debug_port=AUX_DEBUG_PORT,
    # aux_at_port=AUX_AT_PORT,
)
# module = Stress_script(debug_port= DEBUG_PORT, at_port = AT_PORT)
time.sleep(2)
# module.login_Device()
module.dial_net_A
module.test_api_A()
# module.test_api_B()
